package lj.courseinterect.dao;

import lj.courseinterect.dao.i.StudentDao;
import lj.courseinterect.entity.Student;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import java.util.List;

public class JpaStudentDao extends JpaDao<Student, Long> implements StudentDao{

    public JpaStudentDao() {
        super(Student.class);
    }

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        Student stu = this.findByStuNum(username);
//        if (null == stu) {
//            return null;
//        }

        return stu;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Student findByStuNum(String stuNum) {
        final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
        final CriteriaQuery<Student> criteriaQuery = builder.createQuery(this.entityClass);

        Root<Student> root = criteriaQuery.from(this.entityClass);
        Path<String> namePath = root.get("stuNum");
        criteriaQuery.where(builder.equal(namePath, stuNum));

        TypedQuery<Student> typedQuery = this.getEntityManager().createQuery(criteriaQuery);
        List<Student> students = typedQuery.getResultList();

        if (students.isEmpty()) {
            return null;
        }

        return students.iterator().next();
    }


}
